from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import os

from models import Entry, Comment

class AddEntry(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'template/add_entry.html')
        self.response.out.write(template.render(path, {}))
        
    def post(self):
        entry = Entry()
        entry.title = self.request.get('title')
        entry.content = self.request.get('content')
        
        if users.get_current_user():
            entry.author = users.get_current_user()
            
        entry.put()
        self.redirect('/')
        
class MainPage(webapp.RequestHandler):
    def get(self):
        entries = Entry.all()
        entries.order("-create_time")
        
        path = os.path.join(os.path.dirname(__file__), 'template/index.html')
        self.response.out.write(template.render(path, {'entries':entries}))
        
class Login(webapp.RequestHandler):
    def get(self):
        return self.redirect(users.create_login_url('/add_entry'))
        
class ViewEntry(webapp.RequestHandler):
    def get(self):
        id = self.request.get('id')
        entry = Entry.get_by_id(int(id))
        
        path = os.path.join(os.path.dirname(__file__), 'template/view_entry.html')
        self.response.out.write(template.render(path, {'entry':entry}))